package com.kfm.wiki.socket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/ws/{uid}")
@Component
@Slf4j
public class WebSocketServer {

    private static ConcurrentHashMap<String, Session> socketPool = new ConcurrentHashMap<>();

    /**
     * 连接成功
     * @param session
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("uid")String uid) {
        socketPool.put(uid, session);
        log.info("{} 连接成功。 现有 {} 个用户连接", uid, socketPool.size());
    }

    /**
     * 连接关闭
     *
     * @param session
     */
    @OnClose
    public void onClose(Session session, @PathParam("uid")String uid) {
        log.info("{} 连接关闭", uid);
        socketPool.remove(uid);
    }

    /**
     * 接收到消息
     *
     * @param text
     */
    @OnMessage
    public String onMsg(String text, @PathParam("uid")String uid) throws IOException {
        log.info("接收到 {} 的消息：{}", uid, text);
        return "接收到消息：" + text;
    }

    @OnError
    public void onError(Throwable throwable){
        throwable.printStackTrace();
    }

    public static void sendMsg(String message){
        for (String uid: socketPool.keySet()){
            try {
                socketPool.get(uid).getBasicRemote().sendText(message);
                log.info("给 {} 发送消息： {}  成功", uid, message);
            } catch (IOException e) {
                e.printStackTrace();
                log.error("给 {} 发送消息失败", uid);
            }
        }
    }
}
